<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
use tool\Auth;

/**
 * 生产密码
 * @param $password
 * @return string
 */
function makePassword($password) {

    return md5($password . config('admin.salt'));
}

/**
 * 检测密码
 * @param $dbPassword
 * @param $inPassword
 * @return bool
 */
function checkPassword($inPassword, $dbPassword) {
	
    return (makePassword($inPassword) == $dbPassword);
}

/**
 * 获取mysql 版本
 * @return string
 */
function getMysqlVersion() {

    $conn = mysqli_connect(
        config('database.hostname') . ":" . config('database.hostport'),
        config('database.username'),
        config('database.password'),
        config('database.database')
    );

    return mysqli_get_server_info($conn);
}

/**
 * 生成layui子孙树
 * @param $data
 * @return array
 */
function makeTree($data) {

    $res = [];
    $tree = [];

    // 整理数组
    foreach ($data as $key => $vo) {
        $res[$vo['id']] = $vo;
        $res[$vo['id']]['children'] = [];
    }
    unset($data);

    // 查询子孙
    foreach ($res as $key => $vo) {
        if($vo['pid'] != 0){
            $res[$vo['pid']]['children'][] = &$res[$key];
        }
    }

    // 去除杂质
    foreach ($res as $key => $vo) {
        if($vo['pid'] == 0){
            $tree[] = $vo;
        }
    }
    unset($res);

    return $tree;
}

/**
 * 打印调试函数
 * @param $data
 */
function dump($data) {

    echo "<pre>";
    print_r($data);
}

/**
 * 标准返回
 * @param $code
 * @param $data
 * @param $msg
 * @return \think\response\Json
 */
function reMsg($code, $data, $msg) {

    return json(['code' => $code, 'data' => $data, 'msg' => $msg]);
}

/**
 * model返回标准函数
 * @param $code
 * @param $data
 * @param $msg
 * @return array
 */
function modelReMsg($code, $data, $msg) {

    return ['code' => $code, 'data' => $data, 'msg' => $msg];
}

/*
* 获取用户真实IP地址
*/
function get_ip()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $cip = $_SERVER['HTTP_CLIENT_IP'];
    } else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
    } else if (!empty($_SERVER["REMOTE_ADDR"])) {
        $cip = $_SERVER["REMOTE_ADDR"];
    } else {
        $cip = '';
    }
    preg_match("/[\d\.]{7,15}/", $cip, $cips);
    $cip = isset($cips[0]) ? $cips[0] : 'unknown';
    unset($cips);
    return $cip;
}

/**
 * 根据ip定位
 * @param $ip
 * @return string
 * @throws Exception
 */
function getLocationByIp($ip)
{
    $ip2region = new \Ip2Region();
    $info = $ip2region->btreeSearch($ip);

    $info = explode('|', $info['region']);

    $address = '';
    foreach($info as $vo) {
        if('0' !== $vo) {
            $address .= $vo . '-';
        }
    }

    return rtrim($address, '-');
}

/**
 * 按钮检测
 * @param $input
 * @return bool
 */
function buttonAuth($input)
{
    $authModel = Auth::instance();
    return  $authModel->authCheck($input, session('admin_role_id'));
}

/**
 * Notes:发送邮件
 * @param $tomail //收件人地址
 * @param $name //收件人名称
 * @param string $subject //主题
 * @param string $body //内容
 * @param null $attachment //附件
 * @return bool  function send_mail($tomail, $name, $subject = '', $body = '', $attachment = null)
 */
function send_mail($toarremail, $toarratt = null, $totitle, $tobody, $tohtmlpath = null)
{
    $username = config('web.email_username');
    $password = config('web.email_password');
//    $toarremail = config('web.email_address');
    $mail = new PHPMailer();         //实例化PHPMailer对象
    $mail->SMTPOptions = array(
        'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
        )
    );
    $mail->CharSet = 'UTF-8';           //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
    $mail->Encoding = 'base64'; //设置文本编码方式
    $mail->IsSMTP();                    // 设定使用SMTP服务
    $mail->SMTPDebug = 0;               // SMTP调试功能 0=关闭 1 = 错误和消息 2 = 消息
    $mail->SMTPAuth = true;             // 启用 SMTP 验证功能
    $mail->SMTPSecure = 'ssl';          // 使用安全协议
    $mail->Host = "smtp.mxhichina.com";        // 企业邮局域名
    $mail->Port = 465;                  //设置ssl连接smtp服务器的远程服务器端口号 可选465或587

    $mail->Username = $username;    //邮件发送人的用户名(请填写完整的email地址)
    $mail->Password = $password;    // 邮件发送人的 密码 （授权码）

    $mail->From       = $username;   //必填，发件人Email
    $mail->FromName   = "PETCT表单预约";    //必填，发件人昵称
    $mail->Subject    = "PETCT表单预约";              //必填，邮件标题（主题）

//    $mail->SetFrom($username, $username);
    $replyEmail = '';                   //留空则为发件人EMAIL
    $replyName = '';                    //回复名称（留空则为发件人名称）
    $mail->AddReplyTo($replyEmail, $replyName);  //回复的地址

    $mail->Subject = $totitle;   //邮件标题
    $body = $tobody;
    if ($tohtmlpath != null) {
        $body = $mail->getFile($tohtmlpath);//邮件正文内容，提取html文件为其内容
        $body = preg_replace("[\]", '', $body);
    }
    $mail->MsgHTML($body);       //邮件内容

//    $mail->AddAddress($tomail, $name);  //收件人地址，("收件人email","收件人姓名")
    foreach ($toarremail as $adder => $name) {
        $mail->AddAddress($adder, $name);//发送地址
    }

    if (is_array($toarratt)) { // 添加附件
        foreach ($toarratt as $file) {
            is_file($file) && $mail->AddAttachment($file);
        }
    }
    return $mail->Send() ? true : $mail->ErrorInfo;
}
